#define _CRT_SECURE_NO_WARNINGS // 关闭MSVC中不安全的标准库函数的警告
#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"
#ifdef _WIN32
#include <windows.h>
#endif

/// @brief 加载配置文件
/// @param filename 配置文件路径
/// @return 配置文件内容,如果加载失败返回NULL(需要手动释放内存)
char *load_config(const char *filename) {
	FILE *file = fopen(filename, "rb");
	if (file == NULL) {
		perror("配置文件文件打开失败");
		return NULL;
	}

	// 读取文件长度
	fseek(file, 0, SEEK_END);
	const long length = ftell(file);
	fseek(file, 0, SEEK_SET);

	// 分配内存空间
	char *buffer = (char *) malloc(length + 1);
	if (buffer == NULL) {
		perror("无法分配内存");
		fclose(file);
		return NULL;
	}

	// 将文件写入内存
	fread(buffer, 1, length, file);
	fclose(file);

	buffer[length] = '\0';
	return buffer;
}

int main() {
#ifdef _WIN32
	SetConsoleOutputCP(CP_UTF8); // 设置控制台输出编码为UTF-8
#endif

	char *data = load_config("etc/config.json");
	if (data == NULL) {
		return 1;
	}

	// 解析JSON数据
	cJSON *json = cJSON_Parse(data);
	if (json == NULL) {
		printf("Json parse failed.\n");
		free(data);
		return 1;
	}

	// 解析JSON对象
	const cJSON *name = cJSON_GetObjectItemCaseSensitive(json, "name"); // 区分大小写
	if (cJSON_IsString(name) && (name->valuestring != NULL)) {
		printf("name: %s\n", name->valuestring);
	} else {
		printf("name is not a string.\n");
	}

	const cJSON *port = cJSON_GetObjectItem(json, "port"); // 不区分大小写
	printf("port: %d\n", port->valueint);

	// 解析嵌套的JSON对象
	const cJSON *redis     = cJSON_GetObjectItem(json, "redis");
	const cJSON *redisHost = cJSON_GetObjectItem(redis, "host");
	const cJSON *redisPort = cJSON_GetObjectItem(redis, "port");
	printf("redis_host: %s\n", redisHost->valuestring);
	printf("redis_port: %d\n", redisPort->valueint);

	//  解析services
	const cJSON *services = cJSON_GetObjectItem(json, "services");
	for (cJSON *s = services->child; s != NULL; s = s->next) {
		const cJSON *id  = cJSON_GetObjectItem(s, "id");
		const cJSON *srv = cJSON_GetObjectItem(s, "service");
		const cJSON *en  = cJSON_GetObjectItem(s, "enabled");
		printf("id: %d, service: %s, enabled: %d\n", id->valueint, srv->valuestring, en->valueint);
	}

	// 释放内存
	cJSON_Delete(json);
	free(data);
	return 0;
}
